﻿using adb;
using EntityFrameworkCore.UseRowNumberForPaging;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Hosting;
using MQTTnet.AspNetCore;
using SensorCollection.AppCode;
using utils;

namespace SensorCollection
{

    /// <summary>
    /// 
    /// </summary>
    public class Startup
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="configuration"></param>
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        /// <summary>
        /// 
        /// </summary>
        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        /// <summary>
        /// 
        /// </summary>
        /// <param name="services"></param>
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<MyDbContext>(optionsBuilder =>
            {
                object p = optionsBuilder.UseSqlServer(this.Configuration["DBStr"], b => b.UseRowNumberForPaging());
                //optionsBuilder.LogTo(x =>
                //{
                //    Console.WriteLine(x);
                //}, LogLevel.Information);
                optionsBuilder.EnableSensitiveDataLogging(true);
            });
            services.AddDbContext<DeviceDbContext>(optionsBuilder =>
            {
                object p = optionsBuilder.UseSqlServer(this.Configuration["DBDeviceStr"], b => b.UseRowNumberForPaging());
                //optionsBuilder.LogTo(x =>
                //{
                //    Console.WriteLine(x);
                //}, LogLevel.Information);
                optionsBuilder.EnableSensitiveDataLogging(true);
            });
            services.AddDbContext<LogDbContext>(optionsBuilder =>
            {
                object p = optionsBuilder.UseSqlServer(this.Configuration["LogStr"], b => b.UseRowNumberForPaging());
                //optionsBuilder.LogTo(x =>
                //{
                //    Console.WriteLine(x);
                //}, LogLevel.Information);
                optionsBuilder.EnableSensitiveDataLogging(true);
            });
            services.AddControllers().AddJsonOptions(options => {
                options.JsonSerializerOptions.Converters.Add(new DateTimeJsonConverter());
            });

            services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
            services.AddCors(options =>
            {
                options.AddPolicy("Test",
                builder => builder.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod());
            });

            services
                    .AddHostedMqttServer(mqttServer => mqttServer.WithoutDefaultEndpoint())
                    .AddMqttConnectionHandler()
                    .AddConnections();
            services.AddSingleton<RedisUtil>();
            //services.AddMqttWebSocketServerAdapter();

        }
        MqttDealwith mqtt;

        private RedisUtil redis;
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        /// <summary>
        /// 
        /// </summary>
        /// <param name="app"></param>
        /// <param name="env"></param>
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (mqtt == null)
            {
                mqtt = app.ApplicationServices.GetService<MqttDealwith>();
            }
            if (redis == null)
            {
                redis = app.ApplicationServices.GetService<RedisUtil>();
            }
            app.UseCalculateExecutionTime();
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            app.UseCors("Test");

            //app.UseHttpsRedirection();
            app.UseRouting();

            //app.UseEndpoints(endpoints =>
            //{
            //    endpoints.MapMqtt("/mqtt");
            //});
            //app.UseMqttServer(async server =>
            //{

            //});
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapMqtt("/mqtt");
            });

            app.UseMqttServer(server =>
            {
                // Todo: Do something with the server
                this.mqtt = new MqttDealwith(server, this.Configuration,this.redis);
            });

        }

    }
}
